package com.burst.reptile.modular.zp.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.exception.job.TaskException;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.config.CrawlerConfig;
import com.burst.reptile.framework.redis.RedisCache;
import com.burst.reptile.framework.web.entity.LayuiTreeSelect;
import com.burst.reptile.modular.api.vo.CascaderVo;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.mapper.ZpCityMapper;
import com.burst.reptile.modular.zp.service.IZpCityService;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 地区列表 服务实现类
 * </p>
 *
 * @author wujin
 * @since 2020-06-18
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpCityServiceImpl extends ServiceImpl<ZpCityMapper, ZpCity> implements IZpCityService {

	private final RedisCache redisCache;
	
	/**
	 * 项目启动时，初始化省市区
	 */
	@PostConstruct
	public void init() throws SchedulerException, TaskException {
		if(CrawlerConfig.getCityinit()) {
			log.info("------开始初始化省市区------");
			List<CascaderVo> buildCityTreeSelect = this.buildCityTreeSelect(this.list(new QueryWrapper<ZpCity>().eq("disabled", "0").orderByAsc("aid")));
			String jsonString = JSONObject.toJSONString(buildCityTreeSelect);
			byte[] gzip = ZipUtil.gzip(UnicodeUtil.toUnicode(jsonString).getBytes());
			redisCache.setCacheObject(Constants.CITY_KEY, gzip);
			log.info("------初始化省市区完成------");
		}
	}
	
	@Override
	public List<ZpCity> children(String id) {
		return this.list(new QueryWrapper<ZpCity>().eq("parent_id", id).eq("disabled", "0"));
	}

	@Override
	public List<CascaderVo> buildCityTreeSelect(List<ZpCity> citys) {
		List<ZpCity> cityTrees = buildCityTree(citys);
		return cityTrees.stream().map(CascaderVo::new).collect(Collectors.toList());
	}
	
	@Override
	public List<ZpCity> buildCityTree(List<ZpCity> citys) {
		List<ZpCity> returnList = new ArrayList<>();
		List<String> tempList = new ArrayList<>();
		for (ZpCity city : citys) {
			tempList.add(city.getAid());	
		}
		for (Iterator<ZpCity> iterator = citys.iterator(); iterator.hasNext();) {
			ZpCity city = (ZpCity) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(city.getParentId())) {
				recursionFn(citys, city);
				returnList.add(city);
			}
		}
		if (returnList.isEmpty()) {
			returnList = citys;
		}
		return returnList;
	}
	
	/**
	 * 递归列表
	 */
	private void recursionFn(List<ZpCity> list, ZpCity t) {
		// 得到子节点列表
		List<ZpCity> childList = getChildList(list, t);
		t.setChildren(childList);
		for (ZpCity tChild : childList) {
			if (hasChild(list, tChild)) {
				// 判断是否有子节点
				Iterator<ZpCity> it = childList.iterator();
				while (it.hasNext()) {
					ZpCity n = (ZpCity) it.next();
					recursionFn(list, n);
				}
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<ZpCity> getChildList(List<ZpCity> list, ZpCity t) {
		List<ZpCity> tlist = new ArrayList<>();
		Iterator<ZpCity> it = list.iterator();
		boolean has = false;
		while (it.hasNext()) {
			ZpCity n = (ZpCity) it.next();
			if (ToolUtil.isNotEmpty(n.getParentId()) && StrUtil.equals(n.getParentId(), t.getAid())) {
				tlist.add(n);
				has = StrUtil.equals(n.getLevelType(), "3");
			}
		}
		if(has) {
			ZpCity city = new ZpCity();
			city.setAid("-1");
			city.setName("不限");
			tlist.add(0, city);
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<ZpCity> list, ZpCity t) {
		return getChildList(list, t).size() > 0 ? true : false;
	}

	@Override
	public List<ZpCity> selectCityList(ZpCity city) {
		String name = city.getName();
		QueryWrapper<ZpCity> queryWrapper = new QueryWrapper<>();
		if(StrUtil.isNotEmpty(name)) {
			queryWrapper.like("name", name).or().like("short_name", name);
		}
		queryWrapper.orderByAsc("aid");
		return this.list(queryWrapper);
	}

	@Override
	public List<LayuiTreeSelect> buildCityLayuiTreeSelect(List<ZpCity> citys) {
		List<ZpCity> cityTrees = buildCityTree(citys);
		return cityTrees.stream().map(LayuiTreeSelect::new).collect(Collectors.toList());
	}

	@Override
	public Page<ZpCity> getCitys(Page<ZpCity> page, ZpCity city) {
		String aid = city.getAid();
		String name = city.getName();
		QueryWrapper<ZpCity> queryWrapper = new QueryWrapper<ZpCity>();
		if(StrUtil.isNotEmpty(name)) {
			queryWrapper.like("name", name).or().like("short_name", name);
		}
		queryWrapper.and(i -> i.eq("parent_id", aid).or().eq("aid", aid));
		return this.page(page, queryWrapper);
	}
	

	@Override
	public String checkCityNameUnique(ZpCity city) {
		String aid = ToolUtil.isEmpty(city.getAid()) ? "-1" : city.getAid();
		ZpCity info = this.getOne(new QueryWrapper<ZpCity>().eq("name", city.getName()).eq("parent_id", city.getParentId()));
		if (ToolUtil.isNotEmpty(info) && !StrUtil.equals(info.getAid(), aid)) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	@Override
	public int insertCity(ZpCity city) {
		return this.baseMapper.insert(city);
	}

	@Override
	public int selectNormalChildrenCityById(String aid) {
		return this.baseMapper.selectNormalChildrenCityById(aid);
	}

	@Override
	@Transactional
	public int updateCity(ZpCity city) {
		ZpCity newParentCity = this.baseMapper.selectById(city.getParentId());
		ZpCity oldCity = this.baseMapper.selectById(city.getAid());
		if (ToolUtil.isNotEmpty(newParentCity) && ToolUtil.isNotEmpty(oldCity)) {
			String newAncestors = newParentCity.getAncestors() + "," + newParentCity.getAid();
			String oldAncestors = oldCity.getAncestors();
			city.setAncestors(newAncestors);
			updateCityChildren(city.getAid(), newAncestors, oldAncestors);
		}
		int result = this.baseMapper.updateById(city);
		if (UserConstants.DEPT_NORMAL.equals(city.getDisabled())) {
			// 如果该部门是启用状态，则启用该部门的所有上级部门
			updateParentCityStatus(city);
		}
		return result;
	}
	
	/**
	 * 修改该站点的父级站点状态
	 * 
	 * @param city 当前站点
	 */
	private void updateParentCityStatus(ZpCity city) {
		city = this.baseMapper.selectById(city.getAid());
		this.baseMapper.updateCityStatus(city);
	}
	/**
	 * 修改子元素关系
	 * 
	 * @param aid       被修改的站点ID
	 * @param newAncestors 新的父ID集合
	 * @param oldAncestors 旧的父ID集合
	 */
	public void updateCityChildren(String aid, String newAncestors, String oldAncestors) {
		List<ZpCity> children = this.baseMapper.selectChildrenCityById(aid);
		for (ZpCity child : children) {
			child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
		}
		if (children.size() > 0) {
			this.baseMapper.updateCityChildren(children);
		}
	}

	@Override
	public boolean hasChildByAid(String id) {
		int result = this.count(new QueryWrapper<ZpCity>().eq("parent_id", id));
        return result > 0 ? true : false;
	}

	@Override
	public int deleteCityById(String id) {
		return this.baseMapper.deleteById(id);
	}

	@Override
	@Transactional
	public int updateCityStatus(ZpCity city) {
		boolean update = this.update(
				new UpdateWrapper<ZpCity>().set("disabled", city.getDisabled()).eq("aid", city.getAid()));
		if (UserConstants.DEPT_NORMAL.equals(city.getDisabled())) {
			// 如果该部门是启用状态，则启用该部门的所有上级部门
			updateParentCityStatus(city);
		}
		return update ? 1 : 0;
	}
}
